package holdtime.xlxc.activities.main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import holdtime.xlxc.R;
import holdtime.xlxc.base.BaseActivity;
import holdtime.xlxc.tools.util.SharedPreferencesUtil;

public class XscxActivity extends BaseActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSetActionBar = false;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xscx);

        initWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        dialog.show();
        String url;
        if (!TextUtils.isEmpty((String) SharedPreferencesUtil.get(this, "num", "")) && !TextUtils.isEmpty((String) SharedPreferencesUtil.get(this, "add", ""))) {
            url = addressManager.xscx((String) SharedPreferencesUtil.get(this, "add", ""), (String) SharedPreferencesUtil.get(this, "num", ""));

            webView = (WebView) findViewById(R.id.xueshichaxun_webview);
            assert webView != null;
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");

            webView.loadUrl(url);
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });

            webView.setWebViewClient(new WebViewClient() {

                public void onPageFinished(WebView view, String url) {
                    dialog.dismiss();
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public class WebViewJavaScriptInterface {
        private Context context;

        public WebViewJavaScriptInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void closeWebView() {
            finish();
        }

    }
}
